//
//  TeamCentral.m
//  playSerengetiMobile1
//
//  Created by Lita Gratrix on 11/5/09.
//  Copyright 2009 __MyCompanyName__. All rights reserved.
//

#import "TeamCentral.h"
#import "JSON/JSON.h"

#define kViewTag	1	//for tagging our embedded contros for removal at cell recycle time

#define ROW_HEIGHT_FOR_TABLE	30

static NSString *kSectionTitleKey = @"sectionTitleKey";
static NSString *kSourceKey = @"sourceKey";
static NSString *kViewKey = @"viewKey";

@implementation TeamCentral

@synthesize teamCentralTableView;
@synthesize leaders, mostActive, newest;
@synthesize tableSourceArray;
@synthesize appDelegate;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	
//	NSLog(@"Entering TeamCentral viewDidLoad");
	
	self.appDelegate = (playSerengetiMobile1AppDelegate *)[[UIApplication sharedApplication] delegate];

	responseData = [[NSMutableData data] retain];
	NSString *URLString = [NSString stringWithFormat:@"%@team/json", appDelegate.baseURL];
//	NSLog(@"Submit String for TeamCentral is %@\n", URLString);
	NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:URLString]];
	[[NSURLConnection alloc] initWithRequest:request delegate:self];

	self.leaders = [[NSMutableArray alloc] init];
	self.mostActive = [[NSMutableArray alloc] init];
	self.newest = [[NSMutableArray alloc] init];
	self.tableSourceArray = [NSArray arrayWithObjects:
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Teams With The Most Territory", kSectionTitleKey,
							 self.leaders, kSourceKey, nil], 
							
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Most Active Teams", kSectionTitleKey,
							 self.mostActive, kSourceKey, nil],
	
							 [NSDictionary dictionaryWithObjectsAndKeys:
							 @"Newest Teams", kSectionTitleKey,
							 self.newest, kSourceKey,
							 nil],
							nil];
}

- (void)didReceiveMemoryWarning {
	// Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
	
	// Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
	// Release any retained subviews of the main view.
	// e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
}

#pragma mark -
#pragma mark populateViewData Methods

- (void)populateViewData:(NSDictionary *)parsedData{
	NSMutableArray *leadersArray = [parsedData objectForKey:@"leaders"];
	NSMutableArray *mostActiveArray = [parsedData objectForKey:@"mostActive"];
	NSMutableArray *newestArray = [parsedData objectForKey:@"newest"];
	
	[self populateTeamArray:leadersArray ForTableArray:self.leaders];
	[self populateTeamArray:mostActiveArray ForTableArray:self.mostActive];
	[self populateTeamArray:newestArray ForTableArray:self.newest];
	
	[self.teamCentralTableView reloadData];
}

- (void)populateTeamArray:(NSMutableArray *)sourceArray ForTableArray:(NSMutableArray *)tableArray{
//	NSLog(@"Entering populateTeamArray: ForTableArray:");
	if([sourceArray count] == 0){
		//Do Something
	} else {
		[tableArray removeAllObjects];
		int i;
		for (i = 0; i < [sourceArray count]; i++){
			Team *aTeam = [[Team alloc] init];
			NSDictionary *aTeamDic = [sourceArray objectAtIndex:i];
			aTeam.teamId = [[aTeamDic objectForKey:@"id"] integerValue];
			aTeam.teamName = [aTeamDic objectForKey:@"name"];
			
			[tableArray addObject:aTeam];
		}
	}
}

#pragma mark -
#pragma mark NSURLConnectionDelegate

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
	[responseData setLength:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
	[responseData appendData:data];
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
	NSLog(@"Connection failed: %@\n", [error description]);
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
	[connection release];
	
	NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
//	NSLog(@"responseString for TeamCentral reads: %@\n", responseString);
	
	[responseData release];
	
	NSDictionary *parsedData = [responseString JSONValue];
	
	[responseString release];
	
	if (parsedData == nil) {
		NSLog(@"Error in returned data.\n");
	} else {
		[self populateViewData:(NSDictionary *)parsedData];
	}
}	

#pragma mark -
#pragma mark UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
	return [tableSourceArray count];
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
	return [[self.tableSourceArray objectAtIndex: section] valueForKey:kSectionTitleKey];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
	//	NSLog(@"Entering tableView:%@ numberOfRowsInSection:%d", tableView, section);
	NSMutableArray *sectionData = [[self.tableSourceArray objectAtIndex:section] valueForKey:kSourceKey];
	//	NSLog(@"number of expected rows: %d.\n", [sectionData count]);
	return [sectionData count];
}

// to determine specific row height for each cell, override this.
// In this example, each row is determined by its subviews that are embedded.
//
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
		return ROW_HEIGHT_FOR_TABLE;
}

// to determine which UITableViewCell to be used on a given row.
//
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
	UITableViewCell *cell = nil;
	Team *aTeam;
	
	aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	
	static NSString *kDisplayCell_ID = @"DisplayCellID";
	cell = [self.teamCentralTableView dequeueReusableCellWithIdentifier:kDisplayCell_ID];
	if (cell == nil)
	{
		cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:kDisplayCell_ID] autorelease];
		cell.selectionStyle = UITableViewCellSelectionStyleNone;
		cell.accessoryType = UITableViewCellAccessoryDetailDisclosureButton;
	} else {
		// the cell is being recycled, remove old embedded controls
		UIView *viewToRemove = nil;
		viewToRemove = [cell.contentView viewWithTag:kViewTag];
		if (viewToRemove){
			[viewToRemove removeFromSuperview];
		}
	}
	
	UIControl *control = [[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kViewKey];
	[cell.contentView addSubview:control];
	
	cell.textLabel.text = aTeam.teamName;
	
	return cell;
}

- (void)switchAction:(id)sender
{
	// NSLog(@"switchAction: value = %d", [sender isOn]);
}

- (void)pageAction:(id)sender
{
	// NSLog(@"pageAction: current page = %d", [sender currentPage]);
}

#pragma mark -
#pragma mark UITableViewDelegate

// the table's selection has changed, switch to that item's UIViewController
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
	
	Team *aTeam;
	aTeam = [[[self.tableSourceArray objectAtIndex: indexPath.section] valueForKey:kSourceKey] objectAtIndex: indexPath.row];
	
	TeamProfile *aTeamProfileView = [[TeamProfile alloc] initWithNibName:@"TeamProfile" bundle:nil];
	aTeamProfileView.teamId = aTeam.teamId;
	[self.view addSubview:aTeamProfileView.view];	
}


@end
